package com.lvyuely.web.module.controller.func;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.lvyuely.web.module.entity.function.JobTimeExpression;
import com.lvyuely.web.module.job.BaseJob;

@Controller
@RequestMapping("/function/job/time")
public class JobTimeExpressionController {

	private final static Logger logger = Logger.getLogger(JobTimeExpressionController.class);

	@Autowired
	private ApplicationContext ctx;
	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;

	@RequestMapping("reset")
	@ResponseBody
	public String reset() {
		JobTimeExpression expression = new JobTimeExpression();
		// 测试手动输入
		// 设置定时任务ID
		expression.setJob("timeExpressionResetJob");
		// 设置运行serverIP
		expression.setServerIp("10.100.2.205,");
		// 对应触发器ID
		expression.setTrigger("timeExpressionResetJobTrigger");
		// 设置时间规则
		expression.setExpression("0/5 0/1 * * * ?");
		try {
			// 获得JOB对象
			BaseJob job = ctx.getBean(expression.getJob(), BaseJob.class);
			// 设置job运行server
			job.setServerIp(expression.getServerIp());
			// 获得定时任务触发器对象
			CronTriggerBean trigger = ctx.getBean(expression.getTrigger(), CronTriggerBean.class);
			// 触发器时间规则判断（未考虑规则正确性）
			if (trigger != null && StringUtils.isNotEmpty(expression.getExpression()) && !trigger.getCronExpression().equalsIgnoreCase(expression.getExpression())) {
				logger.info("reset job time expression" + JSON.toJSONString(expression));
				// 设置新规则
				trigger.setCronExpression(expression.getExpression());
				// 注销定时任务
				schedulerFactoryBean.destroy();
				// 手动重建定时任务
				schedulerFactoryBean.afterPropertiesSet();
				// 启动任务
				schedulerFactoryBean.start();
			}
		} catch (Throwable t) {
			logger.error("", t);
		}
		return "ok";
	}

}
